const db = uniCloud.database();
const dbCmd = db.command;
const $ = db.command.aggregate;

module.exports = {
  _before: function() {
    // 通用前置处理
  },
  
  /**
   * 获取缴费统计数据
   * @param {Object} params - 统计参数
   * @param {String} params.start_date - 开始日期（可选）
   * @param {String} params.end_date - 结束日期（可选）
   * @param {String} params.student_id - 学生ID（可选）
   * @param {String} params.course_id - 课程ID（可选）
   * @param {String} params.stat_type - 统计类型：daily-日期, monthly-月度, yearly-年度
   * @returns {Object} 缴费统计数据
   */
  async getPaymentStats(params = {}) {
    const { start_date, end_date, student_id, course_id, stat_type = 'daily' } = params;
    
    // 构建查询条件
    const match = {};
    
    // 日期范围条件
    if (start_date && end_date) {
      const startDate = new Date(start_date);
      startDate.setHours(0, 0, 0, 0);
      
      const endDate = new Date(end_date);
      endDate.setHours(23, 59, 59, 999);
      
      match.payment_date = dbCmd.gte(startDate).and(dbCmd.lte(endDate));
    }
    
    // 其他过滤条件
    if (student_id) match.student_id = student_id;
    if (course_id) match.course_id = course_id;
    
    // 只统计已缴费的记录
    match.status = 1;
    
    // 根据统计类型确定分组方式
    let groupField = {};
    
    switch (stat_type) {
      case 'daily':
        groupField = {
          year: { $year: '$payment_date' },
          month: { $month: '$payment_date' },
          day: { $dayOfMonth: '$payment_date' }
        };
        break;
      case 'monthly':
        groupField = {
          year: { $year: '$payment_date' },
          month: { $month: '$payment_date' }
        };
        break;
      case 'yearly':
        groupField = {
          year: { $year: '$payment_date' }
        };
        break;
      default:
        throw new Error('统计类型不正确');
    }
    
    // 执行聚合查询
    const result = await db.collection('payment')
      .aggregate()
      .match(match)
      .group({
        _id: groupField,
        total_amount: { $sum: '$amount' },
        count: { $sum: 1 }
      })
      .sort({
        '_id.year': 1,
        '_id.month': 1,
        '_id.day': 1
      })
      .end()
      .then(res => res.data);
    
    // 格式化结果
    const formattedResult = result.map(item => {
      const { _id, total_amount, count } = item;
      
      let date_key = '';
      let date_label = '';
      
      switch (stat_type) {
        case 'daily':
          date_key = `${_id.year}-${_id.month.toString().padStart(2, '0')}-${_id.day.toString().padStart(2, '0')}`;
          date_label = `${_id.year}年${_id.month}月${_id.day}日`;
          break;
        case 'monthly':
          date_key = `${_id.year}-${_id.month.toString().padStart(2, '0')}`;
          date_label = `${_id.year}年${_id.month}月`;
          break;
        case 'yearly':
          date_key = `${_id.year}`;
          date_label = `${_id.year}年`;
          break;
      }
      
      return {
        date_key,
        date_label,
        total_amount,
        count
      };
    });
    
    // 计算总数
    const totalAmount = formattedResult.reduce((sum, item) => sum + item.total_amount, 0);
    const totalCount = formattedResult.reduce((sum, item) => sum + item.count, 0);
    
    return {
      details: formattedResult,
      stats: {
        total_amount: totalAmount,
        total_count: totalCount
      },
      period: {
        start_date: start_date ? new Date(start_date) : null,
        end_date: end_date ? new Date(end_date) : null
      }
    };
  },
  
  /**
   * 获取欠费统计数据
   * @returns {Object} 欠费统计数据
   */
  async getUnpaidStats() {
    // 获取所有有效的报名记录
    const enrollments = await db.collection('enrollment')
      .aggregate()
      .match({
        status: 1
      })
      .lookup({
        from: 'student',
        localField: 'student_id',
        foreignField: '_id',
        as: 'student'
      })
      .lookup({
        from: 'course',
        localField: 'course_id',
        foreignField: '_id',
        as: 'course'
      })
      .project({
        _id: 1,
        student_id: 1,
        course_id: 1,
        fee: 1,
        discount: 1,
        student: { $arrayElemAt: ['$student', 0] },
        course: { $arrayElemAt: ['$course', 0] }
      })
      .end()
      .then(res => res.data);
    
    // 获取缴费记录
    const enrollmentIds = enrollments.map(e => e._id);
    const payments = await db.collection('payment')
      .where({
        enrollment_id: dbCmd.in(enrollmentIds),
        status: 1 // 已缴费状态
      })
      .field({
        enrollment_id: true,
        amount: true
      })
      .get()
      .then(res => res.data);
    
    // 计算每个报名记录的已缴费总额
    const paymentMap = {};
    payments.forEach(payment => {
      if (!paymentMap[payment.enrollment_id]) {
        paymentMap[payment.enrollment_id] = 0;
      }
      paymentMap[payment.enrollment_id] += payment.amount;
    });
    
    // 筛选出欠费的学生
    const unpaidRecords = enrollments.filter(enrollment => {
      const paidAmount = paymentMap[enrollment._id] || 0;
      return paidAmount < enrollment.fee;
    }).map(enrollment => {
      const paidAmount = paymentMap[enrollment._id] || 0;
      const unpaidAmount = enrollment.fee - paidAmount;
      
      return {
        enrollment_id: enrollment._id,
        student_id: enrollment.student_id,
        course_id: enrollment.course_id,
        student_name: enrollment.student?.name || '',
        course_name: enrollment.course?.name || '',
        grade: enrollment.student?.grade || '',
        class: enrollment.student?.class || '',
        parent_phone: enrollment.student?.parent_phone || '',
        total_fee: enrollment.fee,
        paid_amount: paidAmount,
        unpaid_amount: unpaidAmount,
        payment_rate: Math.round((paidAmount / enrollment.fee) * 100) // 缴费率
      };
    });
    
    // 按缴费率、年级、班级进行统计
    const gradeStats = {};
    const classStats = {};
    const paymentRateStats = {
      unpaid: 0, // 未缴费
      partial: 0, // 部分缴费
      nearly: 0, // 接近缴清 (>= 80%)
    };
    
    unpaidRecords.forEach(record => {
      // 年级统计
      if (record.grade) {
        if (!gradeStats[record.grade]) {
          gradeStats[record.grade] = {
            count: 0,
            total_fee: 0,
            paid_amount: 0,
            unpaid_amount: 0
          };
        }
        
        gradeStats[record.grade].count++;
        gradeStats[record.grade].total_fee += record.total_fee;
        gradeStats[record.grade].paid_amount += record.paid_amount;
        gradeStats[record.grade].unpaid_amount += record.unpaid_amount;
      }
      
      // 班级统计
      if (record.class) {
        if (!classStats[record.class]) {
          classStats[record.class] = {
            count: 0,
            total_fee: 0,
            paid_amount: 0,
            unpaid_amount: 0
          };
        }
        
        classStats[record.class].count++;
        classStats[record.class].total_fee += record.total_fee;
        classStats[record.class].paid_amount += record.paid_amount;
        classStats[record.class].unpaid_amount += record.unpaid_amount;
      }
      
      // 缴费率统计
      const paymentRate = record.payment_rate;
      
      if (paymentRate === 0) {
        paymentRateStats.unpaid++;
      } else if (paymentRate >= 80) {
        paymentRateStats.nearly++;
      } else {
        paymentRateStats.partial++;
      }
    });
    
    // 格式化年级和班级统计结果
    const gradeStatsArray = Object.keys(gradeStats).map(grade => ({
      grade,
      ...gradeStats[grade],
      payment_rate: Math.round((gradeStats[grade].paid_amount / gradeStats[grade].total_fee) * 100)
    }));
    
    const classStatsArray = Object.keys(classStats).map(className => ({
      class: className,
      ...classStats[className],
      payment_rate: Math.round((classStats[className].paid_amount / classStats[className].total_fee) * 100)
    }));
    
    // 计算总数据
    const totalStats = {
      count: unpaidRecords.length,
      total_fee: unpaidRecords.reduce((sum, record) => sum + record.total_fee, 0),
      paid_amount: unpaidRecords.reduce((sum, record) => sum + record.paid_amount, 0),
      unpaid_amount: unpaidRecords.reduce((sum, record) => sum + record.unpaid_amount, 0)
    };
    
    totalStats.payment_rate = Math.round((totalStats.paid_amount / totalStats.total_fee) * 100);
    
    return {
      records: unpaidRecords,
      grade_stats: gradeStatsArray,
      class_stats: classStatsArray,
      payment_rate_stats: paymentRateStats,
      total_stats: totalStats
    };
  },
  
  /**
   * 获取考勤统计数据
   * @param {Object} params - 统计参数
   * @param {String} params.start_date - 开始日期
   * @param {String} params.end_date - 结束日期
   * @param {String} params.student_id - 学生ID（可选）
   * @param {String} params.course_id - 课程ID（可选）
   * @returns {Object} 考勤统计数据
   */
  async getAttendanceStats(params = {}) {
    const { start_date, end_date, student_id, course_id } = params;
    
    if (!start_date || !end_date) {
      throw new Error('开始日期和结束日期不能为空');
    }
    
    // 构建查询条件
    const match = {};
    
    // 日期范围条件
    const startDate = new Date(start_date);
    startDate.setHours(0, 0, 0, 0);
    
    const endDate = new Date(end_date);
    endDate.setHours(23, 59, 59, 999);
    
    match.date = dbCmd.gte(startDate).and(dbCmd.lte(endDate));
    
    // 其他过滤条件
    if (student_id) match.student_id = student_id;
    if (course_id) match.course_id = course_id;
    
    // 执行聚合查询
    const result = await db.collection('attendance')
      .aggregate()
      .match(match)
      .group({
        _id: {
          student_id: '$student_id',
          course_id: '$course_id',
          status: '$status'
        },
        count: { $sum: 1 }
      })
      .lookup({
        from: 'student',
        localField: '_id.student_id',
        foreignField: '_id',
        as: 'student'
      })
      .lookup({
        from: 'course',
        localField: '_id.course_id',
        foreignField: '_id',
        as: 'course'
      })
      .project({
        _id: 0,
        student_id: '$_id.student_id',
        course_id: '$_id.course_id',
        status: '$_id.status',
        count: 1,
        student: { $arrayElemAt: ['$student', 0] },
        course: { $arrayElemAt: ['$course', 0] }
      })
      .end()
      .then(res => res.data);
    
    // 按学生和课程分组整理数据
    const statsMap = {};
    
    result.forEach(item => {
      const key = `${item.student_id}_${item.course_id}`;
      
      if (!statsMap[key]) {
        statsMap[key] = {
          student_id: item.student_id,
          course_id: item.course_id,
          student_name: item.student?.name || '',
          course_name: item.course?.name || '',
          grade: item.student?.grade || '',
          class: item.student?.class || '',
          present: 0,
          absent: 0,
          leave: 0,
          total: 0
        };
      }
      
      // 累计各种状态的数量
      switch (item.status) {
        case 1: // 出勤
          statsMap[key].present += item.count;
          break;
        case 0: // 缺勤
          statsMap[key].absent += item.count;
          break;
        case 2: // 请假
          statsMap[key].leave += item.count;
          break;
      }
      
      statsMap[key].total += item.count;
    });
    
    // 转换为数组并计算出勤率等指标
    const studentStats = Object.values(statsMap).map(stat => ({
      ...stat,
      present_rate: Math.round((stat.present / stat.total) * 100) || 0,
      absent_rate: Math.round((stat.absent / stat.total) * 100) || 0,
      leave_rate: Math.round((stat.leave / stat.total) * 100) || 0
    }));
    
    // 总体考勤统计
    const totalStats = {
      present: studentStats.reduce((sum, stat) => sum + stat.present, 0),
      absent: studentStats.reduce((sum, stat) => sum + stat.absent, 0),
      leave: studentStats.reduce((sum, stat) => sum + stat.leave, 0),
      total: studentStats.reduce((sum, stat) => sum + stat.total, 0)
    };
    
    totalStats.present_rate = Math.round((totalStats.present / totalStats.total) * 100) || 0;
    totalStats.absent_rate = Math.round((totalStats.absent / totalStats.total) * 100) || 0;
    totalStats.leave_rate = Math.round((totalStats.leave / totalStats.total) * 100) || 0;
    
    // 按班级和年级统计
    const gradeStats = {};
    const classStats = {};
    
    studentStats.forEach(stat => {
      // 年级统计
      if (stat.grade) {
        if (!gradeStats[stat.grade]) {
          gradeStats[stat.grade] = {
            present: 0,
            absent: 0,
            leave: 0,
            total: 0
          };
        }
        
        gradeStats[stat.grade].present += stat.present;
        gradeStats[stat.grade].absent += stat.absent;
        gradeStats[stat.grade].leave += stat.leave;
        gradeStats[stat.grade].total += stat.total;
      }
      
      // 班级统计
      if (stat.class) {
        if (!classStats[stat.class]) {
          classStats[stat.class] = {
            present: 0,
            absent: 0,
            leave: 0,
            total: 0
          };
        }
        
        classStats[stat.class].present += stat.present;
        classStats[stat.class].absent += stat.absent;
        classStats[stat.class].leave += stat.leave;
        classStats[stat.class].total += stat.total;
      }
    });
    
    // 格式化年级和班级统计结果
    const gradeStatsArray = Object.keys(gradeStats).map(grade => {
      const stats = gradeStats[grade];
      return {
        grade,
        ...stats,
        present_rate: Math.round((stats.present / stats.total) * 100) || 0,
        absent_rate: Math.round((stats.absent / stats.total) * 100) || 0,
        leave_rate: Math.round((stats.leave / stats.total) * 100) || 0
      };
    });
    
    const classStatsArray = Object.keys(classStats).map(className => {
      const stats = classStats[className];
      return {
        class: className,
        ...stats,
        present_rate: Math.round((stats.present / stats.total) * 100) || 0,
        absent_rate: Math.round((stats.absent / stats.total) * 100) || 0,
        leave_rate: Math.round((stats.leave / stats.total) * 100) || 0
      };
    });
    
    return {
      student_stats: studentStats,
      grade_stats: gradeStatsArray,
      class_stats: classStatsArray,
      total_stats: totalStats,
      period: {
        start_date: startDate,
        end_date: endDate
      }
    };
  },
  
  /**
   * 获取课程报名统计数据
   * @returns {Object} 课程报名统计数据
   */
  async getCourseEnrollmentStats() {
    // 获取所有课程
    const courses = await db.collection('course')
      .orderBy('create_date', 'desc')
      .get()
      .then(res => res.data);
    
    // 获取报名记录
    const enrollmentStats = await db.collection('enrollment')
      .aggregate()
      .match({
        status: 1 // 只统计有效报名
      })
      .group({
        _id: '$course_id',
        student_count: { $sum: 1 },
        total_fee: { $sum: '$fee' },
        total_discount: { $sum: '$discount' }
      })
      .lookup({
        from: 'course',
        localField: '_id',
        foreignField: '_id',
        as: 'course'
      })
      .project({
        _id: 0,
        course_id: '$_id',
        student_count: 1,
        total_fee: 1,
        total_discount: 1,
        course: { $arrayElemAt: ['$course', 0] }
      })
      .end()
      .then(res => res.data);
    
    // 将报名统计数据映射到课程
    const courseEnrollmentMap = {};
    
    enrollmentStats.forEach(stat => {
      courseEnrollmentMap[stat.course_id] = {
        student_count: stat.student_count,
        total_fee: stat.total_fee,
        total_discount: stat.total_discount
      };
    });
    
    // 格式化课程统计结果
    const courseStats = courses.map(course => {
      const stats = courseEnrollmentMap[course._id] || {
        student_count: 0,
        total_fee: 0,
        total_discount: 0
      };
      
      return {
        course_id: course._id,
        course_name: course.name,
        status: course.status,
        fee: course.fee,
        fee_type: course.fee_type,
        fee_type_text: course.fee_type === 1 ? '月度收费' : '按次收费',
        start_date: course.start_date,
        end_date: course.end_date,
        ...stats,
        avg_fee: stats.student_count > 0 ? Math.round(stats.total_fee / stats.student_count) : 0,
        avg_discount: stats.student_count > 0 ? Math.round(stats.total_discount / stats.student_count) : 0
      };
    });
    
    // 计算总统计数据
    const totalStats = {
      active_courses: courseStats.filter(course => course.status === 1).length,
      inactive_courses: courseStats.filter(course => course.status === 0).length,
      total_courses: courseStats.length,
      total_students: courseStats.reduce((sum, course) => sum + course.student_count, 0),
      total_fee: courseStats.reduce((sum, course) => sum + course.total_fee, 0),
      total_discount: courseStats.reduce((sum, course) => sum + course.total_discount, 0)
    };
    
    // 按月度/次数收费类型统计
    const feeTypeStats = {
      monthly: {
        count: courseStats.filter(course => course.fee_type === 1).length,
        student_count: courseStats.filter(course => course.fee_type === 1)
          .reduce((sum, course) => sum + course.student_count, 0),
        total_fee: courseStats.filter(course => course.fee_type === 1)
          .reduce((sum, course) => sum + course.total_fee, 0)
      },
      count_based: {
        count: courseStats.filter(course => course.fee_type === 2).length,
        student_count: courseStats.filter(course => course.fee_type === 2)
          .reduce((sum, course) => sum + course.student_count, 0),
        total_fee: courseStats.filter(course => course.fee_type === 2)
          .reduce((sum, course) => sum + course.total_fee, 0)
      }
    };
    
    return {
      course_stats: courseStats,
      total_stats: totalStats,
      fee_type_stats: feeTypeStats
    };
  },
  
  /**
   * 获取学生统计数据
   * @returns {Object} 学生统计数据
   */
  async getStudentStats() {
    // 获取所有学生
    const students = await db.collection('student')
      .orderBy('create_date', 'desc')
      .get()
      .then(res => res.data);
    
    // 获取报名记录
    const enrollmentStats = await db.collection('enrollment')
      .aggregate()
      .match({
        status: 1 // 只统计有效报名
      })
      .group({
        _id: '$student_id',
        course_count: { $sum: 1 },
        total_fee: { $sum: '$fee' },
        total_discount: { $sum: '$discount' }
      })
      .lookup({
        from: 'student',
        localField: '_id',
        foreignField: '_id',
        as: 'student'
      })
      .project({
        _id: 0,
        student_id: '$_id',
        course_count: 1,
        total_fee: 1,
        total_discount: 1,
        student: { $arrayElemAt: ['$student', 0] }
      })
      .end()
      .then(res => res.data);
    
    // 将报名统计数据映射到学生
    const studentEnrollmentMap = {};
    
    enrollmentStats.forEach(stat => {
      studentEnrollmentMap[stat.student_id] = {
        course_count: stat.course_count,
        total_fee: stat.total_fee,
        total_discount: stat.total_discount
      };
    });
    
    // 按年级和班级分组
    const gradeStats = {};
    const classStats = {};
    
    // 格式化学生统计结果
    const studentStats = students.map(student => {
      const stats = studentEnrollmentMap[student._id] || {
        course_count: 0,
        total_fee: 0,
        total_discount: 0
      };
      
      // 年级统计
      if (student.grade) {
        if (!gradeStats[student.grade]) {
          gradeStats[student.grade] = {
            count: 0,
            active_count: 0,
            course_count: 0,
            total_fee: 0
          };
        }
        
        gradeStats[student.grade].count++;
        
        if (student.status === 1) {
          gradeStats[student.grade].active_count++;
          gradeStats[student.grade].course_count += stats.course_count;
          gradeStats[student.grade].total_fee += stats.total_fee;
        }
      }
      
      // 班级统计
      if (student.class) {
        if (!classStats[student.class]) {
          classStats[student.class] = {
            count: 0,
            active_count: 0,
            course_count: 0,
            total_fee: 0
          };
        }
        
        classStats[student.class].count++;
        
        if (student.status === 1) {
          classStats[student.class].active_count++;
          classStats[student.class].course_count += stats.course_count;
          classStats[student.class].total_fee += stats.total_fee;
        }
      }
      
      return {
        student_id: student._id,
        student_name: student.name,
        grade: student.grade,
        class: student.class,
        status: student.status,
        status_text: student.status === 1 ? '在读' : '退学',
        ...stats
      };
    });
    
    // 格式化年级统计结果
    const gradeStatsArray = Object.keys(gradeStats).map(grade => ({
      grade,
      ...gradeStats[grade],
      avg_courses: gradeStats[grade].active_count > 0 
        ? (gradeStats[grade].course_count / gradeStats[grade].active_count).toFixed(1) 
        : 0,
      avg_fee: gradeStats[grade].active_count > 0 
        ? Math.round(gradeStats[grade].total_fee / gradeStats[grade].active_count) 
        : 0
    }));
    
    // 格式化班级统计结果
    const classStatsArray = Object.keys(classStats).map(className => ({
      class: className,
      ...classStats[className],
      avg_courses: classStats[className].active_count > 0 
        ? (classStats[className].course_count / classStats[className].active_count).toFixed(1) 
        : 0,
      avg_fee: classStats[className].active_count > 0 
        ? Math.round(classStats[className].total_fee / classStats[className].active_count) 
        : 0
    }));
    
    // 计算总统计数据
    const totalStats = {
      total_students: students.length,
      active_students: students.filter(student => student.status === 1).length,
      inactive_students: students.filter(student => student.status === 0).length,
      total_courses: enrollmentStats.reduce((sum, stat) => sum + stat.course_count, 0),
      total_fee: enrollmentStats.reduce((sum, stat) => sum + stat.total_fee, 0),
      total_discount: enrollmentStats.reduce((sum, stat) => sum + stat.total_discount, 0),
      avg_courses_per_student: studentStats.filter(student => student.status === 1).length > 0
        ? (totalStats.total_courses / studentStats.filter(student => student.status === 1).length).toFixed(1)
        : 0,
      avg_fee_per_student: studentStats.filter(student => student.status === 1).length > 0
        ? Math.round(totalStats.total_fee / studentStats.filter(student => student.status === 1).length)
        : 0
    };
    
    return {
      student_stats: studentStats,
      grade_stats: gradeStatsArray,
      class_stats: classStatsArray,
      total_stats: totalStats
    };
  },
  
  /**
   * 获取仪表盘统计数据
   * @returns {Object} 仪表盘统计数据
   */
  async getDashboardStats() {
    try {
      // 确保所有需要的集合存在
      await this._ensureCollection('student');
      await this._ensureCollection('course');
      await this._ensureCollection('enrollment');
      await this._ensureCollection('payment');
      await this._ensureCollection('refund');
      await this._ensureCollection('attendance');
      
      // 定义默认返回结构
      const result = {
        counts: {
          students: { total: 0, active: 0 },
          courses: { total: 0, active: 0 },
          attendance: { total: 0, present: 0 },
          payments: { count: 0, amount: 0 },
          refunds: { count: 0, amount: 0 }
        },
        payment: { recent: [] },
        unpaid: { count: 0 },
        net_income: 0,
        last_updated: new Date()
      };
      
      // 学生统计 - 尝试多种方式查询在读学生
      try {
        // 获取总学生数
        const studentCountResult = await db.collection('student').count();
        result.counts.students.total = studentCountResult.total || 0;
        
        // 方法1：直接查询数字类型status=1的学生
        const activeStudentCountResult1 = await db.collection('student').where({ status: 1 }).count();
        
        // 方法2：使用dbCmd.eq查询
        const activeStudentCountResult2 = await db.collection('student').where({
          status: dbCmd.eq(1)
        }).count();
        
        // 方法3：获取所有学生并手动计数
        const allStudents = await db.collection('student').get();
        let manualCount = 0;
        
        if (allStudents && allStudents.data) {
          allStudents.data.forEach(student => {
            if (student.status === 1 || student.status === '1') {
              manualCount++;
            }
          });
          
          // 输出所有学生的status值以诊断
          console.log('所有学生status值:', allStudents.data.map(s => ({ 
            id: s._id, 
            name: s.name,
            status: s.status, 
            statusType: typeof s.status 
          })));
        }
        
        // 使用手动计数的结果设置活跃学生数
        result.counts.students.active = manualCount;
        
        // 详细诊断日志
        console.log('学生统计详细结果:', {
          total: studentCountResult.total,
          active1: activeStudentCountResult1.total,
          active2: activeStudentCountResult2.total,
          manualCount: manualCount,
          studentSample: allStudents.data.slice(0, 3) // 输出前3个学生样本
        });
      } catch (error) {
        console.error('获取学生统计失败:', error);
      }
      
      // 课程统计
      try {
        const courseCountResult = await db.collection('course').count();
        const activeCourseCountResult = await db.collection('course').where({ status: 1 }).count();
        
        result.counts.courses.total = courseCountResult.total || 0;
        result.counts.courses.active = activeCourseCountResult.total || 0;
      } catch (error) {
        console.error('获取课程统计失败:', error);
      }
      
      // 报名统计
      try {
        const enrollmentCountResult = await db.collection('enrollment').count();
        
        // 检查enrollment集合结构
        const enrollmentSchema = await db.collection('enrollment').limit(1).get();
        let activeEnrollmentCount = 0;
        
        if (enrollmentSchema.data.length > 0 && 'status' in enrollmentSchema.data[0]) {
          const activeEnrollmentCountResult = await db.collection('enrollment').where({ status: 1 }).count();
          activeEnrollmentCount = activeEnrollmentCountResult.total || 0;
        }
        
        result.counts.enrollments.total = enrollmentCountResult.total || 0;
        result.counts.enrollments.active = activeEnrollmentCount;
      } catch (error) {
        console.error('获取报名统计失败:', error);
      }
      
      // 缴费统计
      let totalPaymentAmount = 0;
      try {
        const paymentResult = await db.collection('payment')
          .where({ status: 1 })
          .field({ amount: true })
          .get();
        
        result.counts.payments.count = paymentResult.data.length;
        totalPaymentAmount = paymentResult.data.reduce((sum, payment) => sum + (payment.amount || 0), 0);
        result.counts.payments.amount = totalPaymentAmount;
      } catch (error) {
        console.error('获取缴费统计失败:', error);
      }
      
      // 退费统计
      let totalRefundAmount = 0;
      try {
        const refundResult = await db.collection('refund')
          .where({ status: 1 })
          .field({ amount: true })
          .get();
        
        result.counts.refunds.count = refundResult.data.length;
        totalRefundAmount = refundResult.data.reduce((sum, refund) => sum + (refund.amount || 0), 0);
        result.counts.refunds.amount = totalRefundAmount;
      } catch (error) {
        console.error('获取退费统计失败:', error);
      }
      
      // 计算净收入
      result.net_income = totalPaymentAmount - totalRefundAmount;
      
      // 统计最近30天的缴费情况
      try {
        const thirtyDaysAgo = new Date();
        thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);
        
        const recentPaymentResult = await db.collection('payment')
          .where({
            status: 1,
            payment_date: dbCmd.gte(thirtyDaysAgo)
          })
          .field({ amount: true, payment_date: true })
          .get();
        
        // 按日期分组汇总最近30天的缴费数据
        const dailyPayments = {};
        
        recentPaymentResult.data.forEach(payment => {
          if (!payment.payment_date) return;
          
          try {
            const dateKey = new Date(payment.payment_date).toISOString().split('T')[0];
            if (!dailyPayments[dateKey]) {
              dailyPayments[dateKey] = {
                date: dateKey,
                count: 0,
                amount: 0
              };
            }
            
            dailyPayments[dateKey].count++;
            dailyPayments[dateKey].amount += (payment.amount || 0);
            
            // 将金额向下取整到整数
            dailyPayments[dateKey].amount = Math.floor(dailyPayments[dateKey].amount);
          } catch (e) {
            console.error('处理日期时出错:', e);
          }
        });
        
        result.payment.recent = Object.values(dailyPayments).sort((a, b) => b.date.localeCompare(a.date));
      } catch (error) {
        console.error('获取最近缴费记录失败:', error);
      }
      
      // 获取未缴费学生数据
      try {
        // 先检查集合中是否有足够的数据进行聚合
        const enrollmentCount = await db.collection('enrollment').count();
        
        if (enrollmentCount.total > 0) {
          // 检查enrollment集合结构
          const enrollmentSchema = await db.collection('enrollment').limit(1).get();
          
          if (enrollmentSchema.data.length > 0) {
            // 根据实际集合结构构建匹配条件 - 这里我们简单统计学生ID的去重数量
            const unpaidStudentsResult = await db.collection('enrollment')
              .aggregate()
              .group({
                _id: '$student_id'
              })
              .end();
              
            result.unpaid.count = unpaidStudentsResult.data.length;
          }
        }
      } catch (error) {
        console.error('获取未缴费学生数据失败:', error);
      }
      
      // 考勤统计 - 替换报名统计
      try {
        const attendanceCountResult = await db.collection('attendance').count();
        
        // 统计出勤记录
        const presentCountResult = await db.collection('attendance').where({ status: 1 }).count();
        
        result.counts.attendance.total = attendanceCountResult.total || 0;
        result.counts.attendance.present = presentCountResult.total || 0;
      } catch (error) {
        console.error('获取考勤统计失败:', error);
      }
      
      return result;
    } catch (error) {
      console.error('获取仪表盘统计数据失败:', error);
      // 返回一个空的数据结构，避免前端报错
      return {
        counts: {
          students: { total: 0, active: 0 },
          courses: { total: 0, active: 0 },
          attendance: { total: 0, present: 0 },
          payments: { count: 0, amount: 0 },
          refunds: { count: 0, amount: 0 }
        },
        payment: { recent: [] },
        unpaid: { count: 0 },
        net_income: 0,
        last_updated: new Date(),
        error: error.message  // 添加错误信息方便调试
      };
    }
  }
}; 